package br.com.extrajudicial.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.JDBCException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.ioc.Component;

@Component
public abstract class GenericDao<T> {
	
	@Autowired
	private Session session;
	private final Class<T> persistentClass;
	
	@SuppressWarnings("unchecked")
	public GenericDao() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	public void save(T t) {
		Transaction tx = this.session.beginTransaction();
		try {
			this.session.save(t);
			tx.commit();
		} catch (JDBCException e) {
			tx.rollback();
		}
	}
	
	public void update(T t) {
		Transaction tx = this.session.beginTransaction();
		try {
			this.session.update(t);
			tx.commit();
		} catch (JDBCException e) {
			tx.rollback();
		}
	}
	
	public void delete(T t) {
		Transaction tx = this.session.beginTransaction();
		try {
			this.session.delete(t);
			tx.commit();
		} catch (JDBCException e) {
			tx.rollback();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<T> listAll() {
		return this.session.createCriteria(this.persistentClass).list();
	}
	
	@SuppressWarnings("unchecked")
	public T load(Long id) {
		return (T) this.session.load(this.persistentClass, id);
	}
	
	public void refresh(T t) {
		this.session.refresh(t);
	}

	public Session getSession() {
		return session;
	}
	
}
